<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/oj-logo.svg" />
            <div class="title">鱼 OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item
          v-for="item in menuItems"
          :key="item.key"
          @click="item.type === 'normal' ? doMenuClick(item.key) : null"
        >
          <template v-if="item.type === 'dropdown'">
            <a-dropdown>
              <a-button
                id="menuItems"
                type="text"
                style="color: gray"
                @click.stop="doMenuClick(item.defaultPath)"
              >
                {{ item.name }}
                <icon-down />
              </a-button>
              <template #content>
                <a-doption
                  v-for="option in item.options"
                  :key="option.path"
                  @click="doMenuClick(option.path)"
                >
                  {{ option.name }}
                </a-doption>
              </template>
            </a-dropdown>
          </template>
          <template v-else>
            {{ item.name }}
          </template>
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <div>
        <span v-if="store.state.user.loginUser?.userName">
          {{ store.state.user.loginUser?.userName }}
          <a-button
            type="text"
            size="mini"
            style="color: gray"
            @click="userLogout"
            >登出</a-button
          >
        </span>

        <span v-else>
          <a-space>
            <a-button type="text" size="small" @click="toLogin">登录</a-button>
            <a-button type="text" size="small" @click="toRegister"
              >注册</a-button
            >
          </a-space>
        </span>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import { UserControllerService } from "../../generated";
import message from "@arco-design/web-vue/es/message";
import { IconDown } from "@arco-design/web-vue/es/icon";

const router = useRouter();
const store = useStore();

// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});

// 菜单项配置
const menuItems = computed(() => {
  const items = [];

  // 添加主页
  items.push({
    key: "/",
    name: "主页",
    type: "normal",
  });

  // 添加题目相关下拉菜单
  const questionRoutes = visibleRoutes.value.filter(
    (route) =>
      route.path === "/questions" || // 浏览题目
      route.path === "/question_submit" || // 浏览题目提交
      route.path === "/add/question" || // 创建题目
      route.path === "/manage/question" || // 管理题目
      route.path === "/add_question_by_xml" // 通过xml文件创建题目
  );
  if (questionRoutes.length > 0) {
    items.push({
      key: "/questions",
      name: "题目",
      type: "dropdown",
      defaultPath: "/questions",
      options: questionRoutes.map((route) => ({
        path: route.path,
        name: route.name,
      })),
    });
  }

  // 添加用户相关下拉菜单
  const userRoutes = visibleRoutes.value.filter(
    (route) =>
      route.path === "/manage/user" || // 管理用户
      route.path === "/batch_register" // 批量创建用户
  );
  if (userRoutes.length > 0) {
    items.push({
      key: "/manage/user",
      name: "用户",
      type: "dropdown",
      defaultPath: "/manage/user",
      options: userRoutes.map((route) => ({
        path: route.path,
        name: route.name,
      })),
    });
  }

  return items;
});

// 默认主页
const selectedKeys = ref(["/"]);

// 路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

const doMenuClick = (key: string) => {
  // 移除路径末尾的斜杠，避免重复
  const path = key || "/"; // 处理空路径情况
  router.push(path);
};

const toLogin = () => {
  router.push("/user/login");
};

const toRegister = () => {
  router.push("/user/register");
};

const userLogout = async () => {
  const res = await UserControllerService.userLogoutUsingPost();
  if (res.code === 0) {
    // 0 表示成功
    // 清除用户状态
    store.commit("user/updateUser", {
      userName: null,
      loginUser: null,
    });

    // 跳转到首页（replace 模式不保留历史记录）
    router.push({
      path: "/",
    });
  } else {
    // 使用 Arco 的 message 组件显示错误
    message.error("登出失败，" + res.message);
  }
};
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
}

.logo {
  height: 48px;
}

:deep(.arco-dropdown-option) {
  padding: 8px 16px;
  cursor: pointer;
}

:deep(.arco-dropdown-option:hover) {
  background-color: var(--color-fill-2);
}

#menuItems:hover {
  background-color: cornflowerblue;
  transition: 0.7s;
}
</style>
